#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-syslogd
# REQUIRE: zfs
# BEFORE: syslogd

. /etc/rc.freenas

generate_syslog_conf()
{
	local IFS="|"
	local f="stg_syslogserver stg_sysloglevel"
	eval local $f
	local sf=$(var_to_sf $f)
	local serverhost=""
	local serverport=""

	cp /conf/base/etc/local/syslog-ng.conf.freenas /etc/local/syslog-ng.conf

	fqdn=$(${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "SELECT adv_fqdn_syslog FROM system_advanced")
	if [ "${fqdn}" -eq "1" ]; then
		sed -i "" -e 's/use-fqdn(no)/use-fqdn(yes)/' /etc/local/syslog-ng.conf
	fi

	${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "
	SELECT
		$sf

	FROM
		system_settings

	ORDER BY
		-id

	LIMIT 1
	" | \
	while eval read -r $f; do
		if [ -n "${stg_syslogserver}" ]; then
			if echo "${stg_syslogserver}" | grep -q ":"; then
				serverhost=$(echo ${stg_syslogserver}|cut -d: -f1)
				serverport=$(echo ${stg_syslogserver}|cut -d: -f2)
			else
				serverhost="${stg_syslogserver}"
				serverport="514"
			fi
{
cat << __EOF__
destination loghost { udp("${serverhost}" port(${serverport}) localport(514)); };
log { source(src);  filter(${stg_sysloglevel}); destination(loghost); };
__EOF__
} >> /etc/local/syslog-ng.conf
		fi
	done

}


use_syslog_dataset()
{
	local use

	use="$(${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "
	SELECT
		sys_syslog_usedataset
	FROM
		system_systemdataset
	ORDER BY
		-id
	LIMIT 1
	" | \
	while read -r syslog_usedataset
	do
		if [ "${syslog_usedataset}" = "0" ]
		then
			echo "1"
		else
			if [ "$(/usr/local/bin/midclt call system.is_freenas)" = "False" ]; then
				local failover="$(/usr/local/bin/midclt -q call notifier.failover_status 2> /dev/null)"
				if [ "x${failover}" = "xBACKUP" ]; then
					echo "1"
				else
					echo "0"
				fi
			else
				echo "0"
			fi
		fi
	done
	)"

	return ${use}
}

get_system_dataset()
{

	if system_dataset_enabled
	then
		echo "$(realpath ${FREENAS_SYSTEMDATASET})"
	else
		return 1
	fi

	return 0
}

get_syslog_dataset()
{
	local system_dataset="$(get_system_dataset)"
	local sys_uuid_field

	if [ "$(ha_node)" = "B" ]; then
		sys_uuid_field="sys_uuid_b"
	else
		sys_uuid_field="sys_uuid"
	fi

	if [ -n "${system_dataset}" ]
	then
		echo "${system_dataset}/syslog-$(${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "select ${sys_uuid_field} from system_systemdataset")"
	fi
}

ix_syslogd_start()
{
	RO_FREENAS_CONFIG=$(ro_sqlite ${name} 2> /tmp/${name}.fail && rm /tmp/${name}.fail)
	trap 'rm -f ${RO_FREENAS_CONFIG}' EXIT
	generate_syslog_conf

	if ! use_syslog_dataset
	then
		if [ -L "/var/log" ]
		then
			local rp="$(realpath -q /var/log)"
			if [ -z "${rp}" ]
			then
				rm -f /var/log
				cp -a /conf/base/var/log /var/
			else
				local datestr="$(date +'%Y%m%d%H%M%S')"
				rm -f /var/log
				mv "/var/log" "/var/log.${datestr}"
				cp -a /conf/base/var/log /var/
			fi
		fi
		/usr/local/bin/midclt call core.reconfigure_logging > /dev/null
		return 0
	fi

	local mp="$(get_syslog_dataset)"

	if [ -z "${mp}" ]
	then
		if [ -L "/var/log" ]
		then
			local rp="$(realpath -q /var/log)"
			if [ -z "${rp}" ]
			then
				rm -f /var/log
				cp -a /conf/base/var/log /var/
			else
				local datestr="$(date +'%Y%m%d%H%M%S')"
				rm -f /var/log
				mv "/var/log" "/var/log.${datestr}"
				cp -a /conf/base/var/log /var/
			fi
		fi

		/usr/local/bin/midclt call core.reconfigure_logging > /dev/null

		return 0
	fi

	#
	#	log directory exists, pick up any new files or
	#	directories and create them. Existing files will be
	#	appended. This is done this way so that ownership and
	#	permissions are always preserved.
	#
	if [ -d "${mp}/log" ]
	then

		#
		#	Pick up any new directories and sync them
		#
		if [ ! -L /var/log ]; then
			for dir in $(find /var/log/ -type d)
			do
				local dst="${mp}/log/${dir#/var/log/}"
				if [ ! -d "${dst}" ]
				then
					/usr/local/bin/rsync -avz ${dir}/* ${dst}/ >/dev/null 2>&1
				fi
			done

		fi

		#
		#	Find all files that are not a directory and see if
		#	they exist. If the file exists already, append to
		#	it, otherwise, copy it over.
		#
		if [ ! -L /var/log ]; then
			for file in $(find /var/log/ ! -type d)
			do
				local dst="${mp}/log/${file#/var/log/}"
				if [ ! -f "${dst}" ]
				then
					cp -p ${file} ${dst}
				else
					cat ${file} >> ${dst}
				fi
			done
		fi

	#
	#	This is the first time syslog is going to log to this
	#	directory, so create the log directory and sync files.
	#
	else
		cp -a /conf/base/var/log ${mp}/
		chmod 755 ${mp}/log
		chown root:wheel ${mp}/log

		/usr/local/bin/rsync -avz /var/log/* ${mp}/log/ >/dev/null 2>&1
	fi

	if [ ! -L "/var/log" -o ! -e "/var/log" ]
	then
		local datestr="$(date +'%Y%m%d%H%M%S')"
		mv "/var/log" "/var/log.${datestr}"
		ln -s "${mp}/log" "/var/log"
	fi

	/usr/local/bin/midclt call core.reconfigure_logging > /dev/null

	return 0
}

name="ix-syslogd"
start_cmd='ix_syslogd_start'
stop_cmd=':'
        
load_rc_config $name
run_rc_command "$1"
